const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const merge = require("webpack-merge");
const glob = require("glob");

var vueLoaderConfig = require("./build/vue-loader.conf");

function resolve(dir) {
return path.join(__dirname, dir)
}

let entryHtml = glob.sync("./public/*.html");
let entryJs = glob.sync("./src/*.js");
let utils = {
    getEntery() {
        let entry = {};
        entryJs.forEach(filePath => {
            let filename = filePath.substring(
                filePath.lastIndexOf("/") + 1,
                filePath.lastIndexOf(".")
            );
            entry[filename] = filePath;
        });
        return entry;
    },
    getHtml() {
        let plugin = [];
        entryHtml.forEach(filePath => {
            let filename = filePath.substring(
                filePath.lastIndexOf("/") + 1,
                filePath.lastIndexOf(".")
            );
            let conf = {
                // 模板来源
                template: filePath,
                // 文件名称
                filename: filename + ".html",
                // 页面模板需要加对应的js脚本，如果不加这行则每个页面都会引入所有的js脚本
                chunks: ["manifest", "vendor", filename],
                inject: true,
                cache: true
            };
            if (process.env.NODE_ENV === "production") {
                conf = merge(conf, {
                    minify: {
                        removeComments: true,
                        collapseWhitespace: true,
                        removeAttributeQuotes: true
                    },
                    chunksSortMode: "dependency"
                });
            }
            plugin.push(new HtmlWebpackPlugin(conf));
        });
        return plugin;
    }
};

function buildRouter(app,url,name){
    let html = `<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1,user-scalable=0">
        <title>新闻</title>
        <script>
          !function(e,t){function i(){var t=n.getBoundingClientRect().width;t/s>750&&(t=750*s);var i=t/10;n.style.fontSize=i+"px",d.rem=e.rem=i}var a,r=e.document,n=r.documentElement,o=r.querySelector('meta[name="viewport"]'),l=r.querySelector('meta[name="flexible"]'),s=0,m=0,d=t.flexible||(t.flexible={});if(o){console.warn("将根据已有的meta标签来设置缩放比例");var c=o.getAttribute("content").match(/initial\-scale=([\d\.]+)/);c&&(m=parseFloat(c[1]),s=parseInt(1/m))}else if(l){var p=l.getAttribute("content");if(p){var u=p.match(/initial\-dpr=([\d\.]+)/),f=p.match(/maximum\-dpr=([\d\.]+)/);u&&(s=parseFloat(u[1]),m=parseFloat((1/s).toFixed(2))),f&&(s=parseFloat(f[1]),m=parseFloat((1/s).toFixed(2)))}}if(!s&&!m){var v=(e.navigator.appVersion.match(/android/gi),e.navigator.appVersion.match(/iphone/gi)),b=e.devicePixelRatio;s=v?b>=3&&(!s||s>=3)?3:b>=2&&(!s||s>=2)?2:1:1,m=1/s}if(n.setAttribute("data-dpr",s),!o)if(o=r.createElement("meta"),o.setAttribute("name","viewport"),e.webPageScalable?o.setAttribute("content","initial-scale="+m+", user-scalable=yes"):o.setAttribute("content","initial-scale="+m+", maximum-scale="+m+", minimum-scale="+m+", user-scalable=no viewport-fit=cover"),n.firstElementChild)n.firstElementChild.appendChild(o);else{var h=r.createElement("div");h.appendChild(o),r.write(h.innerHTML)}e.addEventListener("resize",function(){clearTimeout(a),a=setTimeout(i,300)},!1),e.addEventListener("pageshow",function(e){e.persisted&&(clearTimeout(a),a=setTimeout(i,300))},!1),"complete"===r.readyState?r.body.style.fontSize=12*s+"px":r.addEventListener("DOMContentLoaded",function(e){r.body.style.fontSize=12*s+"px"},!1),i(),d.dpr=e.dpr=s,d.refreshRem=i,d.rem2px=function(e){var t=parseFloat(e)*this.rem;return"string"==typeof e&&e.match(/rem$/)&&(t+="px"),t},d.px2rem=function(e){var t=parseFloat(e)/this.rem;return"string"==typeof e&&e.match(/px$/)&&(t+="rem"),t}}(window,window.lib||(window.lib={}));document.documentElement.addEventListener('touchstart', function (event) {         if (event.touches.length > 1) {           event.preventDefault();         }       }, false);          var lastTouchEnd = 0;       document.documentElement.addEventListener('touchend', function (event) {         var now = Date.now();         if (now - lastTouchEnd <= 300) {           event.preventDefault();         }         lastTouchEnd = now;       }, false); 
        </script>
        <link href="${name}.css" rel="stylesheet">
      </head>
      <body>
        <div id="app"></div>
        <script src="/js/config.js"></script>
        <script src="/js/jquery.min.js"></script>
        <script src="/js/webuploader/webuploader.html5only.min.js"></script>
        <script type="text/javascript" src="vendor.js"></script>
        <script type="text/javascript" src="${name}.js"></script>
      </body>
    </html>`
    app.get(url, function(req, res) {
      res.send(html);
    });
}

module.exports = {
    entry: utils.getEntery(),
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "public")
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            'swiper$':'swiper/dist/js/swiper.js',
            '@': resolve('src'),
            'pages': resolve('src/pages'),
            'components': resolve('src/components')
        }
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: "vue-loader",
                options: vueLoaderConfig
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ["css-loader?importLoaders=1", "postcss-loader"]
                })
            },
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: [
                        "css-loader?importLoaders=1",
                        "postcss-loader",
                        "less-loader"
                    ]
                })
            },
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: "file-loader",
                options: {
                    name: "[name].[ext]?[hash]"
                }
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"dev"'
            }
        }),
        // new CleanWebpackPlugin(['dist']),
        // new webpack.HotModuleReplacementPlugin(),
        new ExtractTextPlugin({
            filename: "[name].css",
            disable: false,
            allChunks: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            minChunks: function(module) {
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(
                        path.join(__dirname, "../node_modules")
                    ) === 0
                );
            }
        })
    ],
    devtool: "cheap-source-map",
    devServer: {
        before(app){
            buildRouter(app,'/','index');
            entryHtml.forEach(item=>{
                let url = item.replace('./public','');
                let name = url.match(/\/(\S*).html/)[1];
                buildRouter(app,url,name);
            }) 
          },
        contentBase: "./public",
        host: "0.0.0.0",
        hotOnly: false
    }
};
